package cn.tedu.coolshark.Controller;

import cn.tedu.coolshark.mapper.ProductMapper;
import cn.tedu.coolshark.pojo.dto.ProductDto;
import cn.tedu.coolshark.pojo.entity.Product;
import cn.tedu.coolshark.pojo.vo.ProductAdminVo;
import cn.tedu.coolshark.pojo.vo.ProductUpdateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    ProductMapper mapper;

    //处理添加商品的请求
    @RequestMapping("/insert")
    public void insert(@RequestBody ProductDto productDto) {
        System.out.println("productDto = " + productDto);
        //把dto装进entity
        Product product = new Product();
        BeanUtils.copyProperties(productDto, product);
        product.setCreated(new Date());
        product.setViewCount(0);
        mapper.insert(product); //创建ProductMapper 实现insert方法
    }

    //处理获取所有商品数据的请求
    @RequestMapping("/select")
    public List<ProductAdminVo> select() {
        return mapper.selectForAdmin();
    }

    //处理删除商品的请求
    @RequestMapping("/delete")
    public void delete(int id){
        String url = mapper.selectUrlById(id);
        new File("d:/files"+url).delete();
        mapper.deleteById(id);
    }

    //处理通过地址栏中的id查询商品详情的请求
    @RequestMapping("/selectById")
    public ProductUpdateVo selectById(int id){
        return mapper.selectById(id);
    }

}
